package com.hpin.mlxteacher.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.bean.BabayTreeData;
import com.hpin.mlxteacher.bean.BabyTreeComment;
import com.hpin.mlxteacher.bean.BabyTreeCreator;
import com.hpin.mlxteacher.bean.SimpleResult;
import com.hpin.mlxteacher.fragment.BabyTreeFragment;
import com.hpin.mlxteacher.ui.HomeActivity;
import com.hpin.mlxteacher.utils.AbDateUtil;
import com.hpin.mlxteacher.utils.CommonUtils;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.DensityUtil;
import com.hpin.mlxteacher.utils.HttpUtil;
import com.hpin.mlxteacher.utils.LogUtil;
import com.hpin.mlxteacher.widget.CircleImageView;
import com.hpin.mlxteacher.widget.GridViewForScrollView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Aaron on 15/7/30.
 */
public class BabyTreeAdapter extends BaseAdapter {

    private Context ctx;
    private List<BabayTreeData> babayTreeDatas;
    private View fragmentView;
    private HomeActivity hActivity;
    private DisplayImageOptions options;
    private SharedPreferences sp;
//    private ProgressDialog dialog;

//    //屏幕的宽
//    private final int screenWidth;

    public BabyTreeAdapter(Context ctx, List<BabayTreeData> babayTreeDatas) {
        this.ctx = ctx;
        this.babayTreeDatas = babayTreeDatas;

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_head_default)
                .showImageForEmptyUri(R.drawable.icon_head_default)
                .showImageOnFail(R.drawable.icon_head_default)
                .resetViewBeforeLoading(true)
                .cacheOnDisk(true).cacheInMemory(true)
                .cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new SimpleBitmapDisplayer()).build();

        sp = ctx.getSharedPreferences(Constant.CONFIG, ctx.MODE_PRIVATE);
//        screenWidth = CommonUtils.getScreenSize(ctx)[0];
    }

    @Override
    public int getCount() {
//        LogUtil.e("TAG", "getCount" + sizes.size());
        return babayTreeDatas.size();
    }

    public void setBabayTreeDatas(List<BabayTreeData> babayTreeDatas) {
        this.babayTreeDatas = babayTreeDatas;
    }

    public void setFragmentView(View fragmentView) {
        this.fragmentView = fragmentView;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;

        if (convertView == null) {
            convertView = View.inflate(ctx, R.layout.item_baby_tree, null);
            viewHolder = new ViewHolder();
            viewHolder.iv_head_pic = (CircleImageView) convertView.findViewById(R.id.iv_head_pic);
//            viewHolder.iv_share = (ImageView) convertView.findViewById(R.id.iv_share);
            viewHolder.iv_comment = (ImageView) convertView.findViewById(R.id.iv_comment);
            viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            viewHolder.tv_content = (TextView) convertView.findViewById(R.id.tv_content);
            viewHolder.tv_loaction = (TextView) convertView.findViewById(R.id.tv_loaction);
            viewHolder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
            viewHolder.tv_delete = (TextView) convertView.findViewById(R.id.tv_delete);

            viewHolder.gv_photos = (GridViewForScrollView) convertView.findViewById(R.id.gv_photos);
            viewHolder.ll_comments = (LinearLayout) convertView.findViewById(R.id.ll_comments);

            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        if (babayTreeDatas.get(position) != null && babayTreeDatas.get(position).creator != null) {

            //头像
            ImageLoader.getInstance().displayImage(babayTreeDatas.get(position).creator.imgUrl, viewHolder.iv_head_pic,
                    options);
            //发宝宝树的人
            viewHolder.tv_name.setText(babayTreeDatas.get(position).creator.nickName);

            //是否显示删除按钮
            viewHolder.tv_delete.setVisibility(ctx.getSharedPreferences(Constant.CONFIG, ctx.MODE_PRIVATE)
                    .getString(Constant.id, "0").equals(babayTreeDatas.get(position).creator.id) ? View.VISIBLE : View.INVISIBLE);

        }

        if (babayTreeDatas.get(position) != null && babayTreeDatas.get(position).tree != null) {

            ArrayList<String> list = new ArrayList<String>();
            //图片
            for (int i = 0; i < babayTreeDatas.get(position).imgList.size(); i++) {
                list.add(babayTreeDatas.get(position).imgList.get(i));
            }

            ShowImageAdapter imageAdapter = new ShowImageAdapter(ctx, list);

            if (list.size() == 1) {//如果只有一张图片
                viewHolder.gv_photos.setNumColumns(1);

                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                viewHolder.gv_photos.setLayoutParams(lp);

            } else if (list.size() == 4) {//四张图片,显示正方形
                viewHolder.gv_photos.setNumColumns(2);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(viewHolder.gv_photos.getLayoutParams());
                lp.setMargins(0, 0, DensityUtil.dip2px(ctx, 85), 0);
                viewHolder.gv_photos.setLayoutParams(lp);

            } else {//其他情况
                viewHolder.gv_photos.setNumColumns(3);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                viewHolder.gv_photos.setLayoutParams(lp);
            }

            viewHolder.gv_photos.setAdapter(imageAdapter);

//            final ArrayList<String> photoLists = list;
//
//            viewHolder.gv_photos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//                @Override
//                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//
////                  Toast.makeText(ctx, "图片的点击事件" + i, Toast.LENGTH_SHORT).show();
//                    Intent mIntent = new Intent(ctx, PreviewPhotoActivity.class);
//                    mIntent.putExtra("position", i);
//                    mIntent.putStringArrayListExtra("preUrlPhotos", photoLists);
//                    ctx.startActivity(mIntent);
//
//                }
//
//            });
            //内容
            viewHolder.tv_content.setText(babayTreeDatas.get(position).tree.content);

            //发布时间
            viewHolder.tv_time.setText(AbDateUtil.formatDateStr2Desc(babayTreeDatas.get(position).tree.createTime, AbDateUtil.dateFormatYMDHM));

            //发布地点
            viewHolder.tv_loaction.setText(babayTreeDatas.get(position).tree.address);

        }

        final LinearLayout temp_ll_comments = viewHolder.ll_comments;

        //设置评论数据
        setCommentData(position, temp_ll_comments);

        viewHolder.iv_comment.setOnClickListener(new View.OnClickListener() {  //评论
            @Override
            public void onClick(View v) {

                commentClick(position, temp_ll_comments, null, null);

            }
        });

        viewHolder.tv_delete.setOnClickListener(new View.OnClickListener() {  //删除
            @Override
            public void onClick(View v) {   //删除

                if (babayTreeDatas.get(position).tree != null)

                    //弹出删除提醒
                    deleteConfirm(babayTreeDatas.get(position).tree.id, position);

            }
        });

//        viewHolder.iv_share.setOnClickListener(new View.OnClickListener() {  //分享
//            @Override
//            public void onClick(View v) {
//
//                showShareDialog(babayTreeDatas.get(position).tree.content, Constant.SHAREBABYTREE + babayTreeDatas.get(position).tree.id);
//
//            }
//        });

        return convertView;
    }

    /**
     * 弹出删除提示
     *
     * @param id
     * @param position
     */
    private void deleteConfirm(final String id, final int position) {

        new AlertDialog.Builder(ctx).setCancelable(true).setTitle("提示").setMessage("确定删除吗?").setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                dialogInterface.dismiss();

            }
        }).setPositiveButton("删除", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                dialogInterface.dismiss();
                //删除
                deleteBabyTree(id, position);
            }
        }).show();

    }

    /**
     * 删除宝宝树
     *
     * @param id       删除的宝宝树的id
     * @param position 删除的集合中对应的position
     */
    private void deleteBabyTree(String id, final int position) {
        BabyTreeCreator bean = new BabyTreeCreator();
        bean.token = sp.getString(Constant.token, "");
        bean.tid = id;

        HttpUtil.setPostRequest("删除中...", ctx, Constant.WEB_ROOT + Constant.DELTREE,
                JSONObject.toJSONString(bean), BabyTreeFragment.class.getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            org.json.JSONObject result = new org.json.JSONObject(str);

                            if (result.getInt("code") == Constant.SUCCESS) {
                                //删除成功
                                babayTreeDatas.remove(position);
                                notifyDataSetChanged();

                            } else {

                                Toast.makeText(ctx, Constant.showErrorMsg(result.getInt("code"), ctx), Toast.LENGTH_SHORT).show();
                            }

                        } catch (Exception e) {
                            Toast.makeText(ctx, Constant.NODATA, Toast.LENGTH_SHORT).show();
                        }

                    }
                }, null);

    }

//    /**
//     * @param content 分享的内容
//     * @param url     分享的url
//     */
//    private void showShareDialog(final String content, final String url) {
//
//        dialog = new ProgressDialog(ctx);
//
//        dialog.setCanceledOnTouchOutside(true);
//        dialog.show();
//
//        dialog.setContentView(R.layout.layout_share);
//
//        TextView tv_wechat_circle = (TextView) dialog.findViewById(R.id.tv_wechat_circle);
//        TextView tv_wechat_friend = (TextView) dialog.findViewById(R.id.tv_wechat_friend);
//
//        //微信好友
//        tv_wechat_friend.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                if (dialog != null && dialog.isShowing()) {
//                    dialog.dismiss();
//                }
//
//                share(content, url, Wechat.NAME);
//
//            }
//        });
//
//        //微信朋友圈
//        tv_wechat_circle.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                if (dialog != null && dialog.isShowing()) {
//                    dialog.dismiss();
//                }
//
//                share(content, url, WechatMoments.NAME);
//
//            }
//        });
//
//    }

//    /**
//     * 分享
//     */
//    private void share(String title, String url, String platform) {
//        ShareSDK.initSDK(ctx);
//
//        Platform.ShareParams sp = new Platform.ShareParams();
//        sp.setTitle(title);
//        sp.setText(title);
//        sp.setImageUrl("http://liaoning.sinaimg.cn/2014/1111/U10435P1195DT20141111220802.jpg");
//        sp.setImagePath("http://liaoning.sinaimg.cn/2014/1111/U10435P1195DT20141111220802.jpg");
//        sp.setImageData(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.ic_launcher));
////        sp.setSiteUrl(url);
//        sp.setUrl(url);
//        sp.setShareType(Wechat.SHARE_WEBPAGE);
////        sp.setShareType(Wechat.SHARE_IMAGE);
//        //分享的平台
//        Platform wechat = ShareSDK.getPlatform(platform);
//
//        wechat.setPlatformActionListener(new PlatformActionListener() {
//            @Override
//            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//                LogUtil.e("TAG", "分享完成");
//            }
//
//            @Override
//            public void onError(Platform platform, int i, Throwable throwable) {
//
//                LogUtil.e("TAG", "分享失败" + i + throwable.getMessage() + "," + throwable.getCause());
////                Toast.makeText(ctx, "分享失败==" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onCancel(Platform platform, int i) {
//                LogUtil.e("TAG", "分享取消");
//            }
//        });
//        wechat.share(sp);
//
////        OnekeyShare oks = new OnekeyShare();
////        // 分享时Notification的图标和文字
////        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
////        oks.setTitle(title);
////        oks.setNotification(R.drawable.ic_launcher, ctx.getString(R.string.app_name));
////        oks.setText("明路星家长端测试");
////        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
////        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
////        // url仅在微信（包括好友和朋友圈）中使用
////        oks.setUrl(url);
//////            oks.setImageUrl("http://123.57.53.133:8080/sgj/images/sgllogo.png");
////        // 启动分享GUI
////        oks.show(ctx);
//    }

    /**
     * 设置评论数据
     */
    private void setCommentData(final int position, final LinearLayout temp_ll_comments) {
        //评论列表
        List<BabyTreeComment> commentsList = babayTreeDatas.get(position).comment;

        //如果没有评论数据 不需要背景
        if (commentsList == null || commentsList.size() == 0) {
            temp_ll_comments.setVisibility(View.GONE);
        } else {
            temp_ll_comments.setVisibility(View.VISIBLE);
        }

        //先移除所有的子view,然后再添加评论内容
        temp_ll_comments.removeAllViews();

        for (int i = 0; i < commentsList.size(); i++) {

            BabyTreeComment c = commentsList.get(i);
            View commentView = View.inflate(ctx, R.layout.item_comment, null);
            temp_ll_comments.addView(commentView);

            TextView tv_comment = (TextView) commentView.findViewById(R.id.tv_comment);//评论人的名字
            TextView tv_reply = (TextView) commentView.findViewById(R.id.tv_reply);//回复
            TextView tv_comment_to = (TextView) commentView.findViewById(R.id.tv_comment_to);//被评论人的名字
            TextView tv_comment_content = (TextView) commentView.findViewById(R.id.tv_comment_content);//评论内容

            //设置评论人姓名
            if (c.fromId != null && c.fromId.equals(sp.getString(Constant.id, ""))) {
                tv_comment.setText("我");
            } else {
                tv_comment.setText(CommonUtils.isNull(c.fromName) ? "" : c.fromName);
            }

            //设置评论内容
            tv_comment_content.setText(CommonUtils.isNull(c.content) ? "" : c.content);

            //判断有无被评论人
            if (CommonUtils.isNull(c.toId)) {   //没有被评论人

                tv_reply.setText("");
                tv_comment_to.setVisibility(View.GONE);

            } else {  //有被评论人

                tv_reply.setText("回复");
                tv_comment_to.setVisibility(View.VISIBLE);
                //看 被评论人是否是自己,如果是自己 则显示 我
                if (c.toId != null && c.toId.equals(sp.getString(Constant.id, ""))) {
                    tv_comment_to.setText("我");
                } else {
                    //被评论人不是我
                    tv_comment_to.setText(c.toName);
                }

                //判断评论人和被评论人是否是同一个人 如果是同一个人则显示 某人: (相当于没有被评论人)
                if (c.fromId != null && c.toId != null &&
                        c.toId.equals(c.fromId)) {

                    tv_reply.setText("");
                    tv_comment_to.setVisibility(View.GONE);

                }

            }

            final List<BabyTreeComment> tempCommentsList = commentsList;
            final int temp = i;
            //每条评论信息的点击事件
            commentView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    //被评论人昵称 (取的是该条评论的 评论人的名称)
                    String name = tempCommentsList.get(temp).fromName;
                    //被评论人id (取的是该条评论的 评论人的id)
                    String id = tempCommentsList.get(temp).fromId;
                    //弹出评论框
                    commentClick(position, temp_ll_comments, name, id);
                }
            });
        }

    }

    /**
     * @param position         被评论的宝宝树的position
     * @param temp_ll_comments 存放评论内容的线性布局
     * @param to_name          被评论人的昵称
     * @param to_id            被评论人的id
     */
    private void commentClick(final int position, final LinearLayout temp_ll_comments, final String to_name, final String to_id) {

        if (fragmentView != null) {

            if (ctx instanceof HomeActivity) {
                hActivity = (HomeActivity) ctx;
            }

            final RelativeLayout rl_bottom_comment = (RelativeLayout) fragmentView.findViewById(R.id.rl_bottom_comment);
            Button btn_comment = (Button) fragmentView.findViewById(R.id.btn_comment);
            final EditText et_comment = (EditText) fragmentView.findViewById(R.id.et_comment);

            rl_bottom_comment.setVisibility(View.VISIBLE);

            InputMethodManager inputManager = (InputMethodManager)
                    et_comment.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

            et_comment.setText("");

            if (CommonUtils.isNull(to_id) || sp.getString(Constant.id, "").equals(to_id)) {//没有被评论人 , 或者被评论人是我自己
                et_comment.setHint(ctx.getResources().getString(R.string.my_comment));
            } else {
                et_comment.setHint("回复：" + to_name);
            }
//                    et_comment.bringToFront();

            //隐藏和显示 评论输入框的监听
            fragmentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {

//                    LogUtil.e("tag", "rootHigh==>" + fragmentView.getRootView().getHeight() +
//                            ",fragmentHigh==>" + fragmentView.getHeight());

                    if (fragmentView.getRootView().getHeight() - fragmentView.getHeight() < 250) {
                        //小于250说明 软键盘隐藏了
                        if (hActivity != null) {
                            //评论输入框隐藏
                            rl_bottom_comment.setVisibility(View.GONE);
                            //底部按钮 显示出来
                            hActivity.showButtom();

                        }

                    } else {
                        //软键盘显示出来了
                        if (hActivity != null) {
                            //底部按钮隐藏
                            hActivity.hitButtom();
                            //输入框显示
                            rl_bottom_comment.setVisibility(View.VISIBLE);
                            et_comment.requestFocus();
                        }
                    }

                }
            });

            btn_comment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    LogUtil.e("TAG", "====发表评论====");

                    if (CommonUtils.isNull(et_comment.getText().toString().trim())) {
                        Toast.makeText(ctx, "请输入评论内容", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    //发表评论
                    makeComment(et_comment.getText().toString().trim(), babayTreeDatas.get(position).tree.id, position, temp_ll_comments
                            , to_name, to_id);

                }
            });

        }

    }

    /**
     * 发表评论
     *
     * @param comment          评论内容
     * @param babyTreeId       被评论的宝宝树的
     * @param position         被评论的宝宝树的条目position
     * @param temp_ll_comments 用于添加评论内容的线性布局
     */
    private void makeComment(final String comment, String babyTreeId, final int position, final LinearLayout temp_ll_comments,
                             final String to_name, final String to_id) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));
        j.put("content", comment);
        j.put("tid", babyTreeId);
        j.put("to_id", CommonUtils.isNull(to_id) ? "" : to_id);
        j.put("to_name", CommonUtils.isNull(to_name) ? "" : to_name);

        HttpUtil.setPostRequest("评论中...", ctx, Constant.WEB_ROOT + Constant.SENDCOMMENT,
                j.toJSONString(), BabyTreeFragment.class.getName(),
                new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            SimpleResult result = JSONObject.parseObject(str, SimpleResult.class);

                            if (result.code == Constant.SUCCESS) {

                                BabyTreeComment c = new BabyTreeComment();
                                c.content = comment; //评论内容
                                c.fromName = "我"; //评论人
                                c.toName = to_name; //被评论人
                                c.toId = to_id;
                                babayTreeDatas.get(position).comment.add(c);
                                setCommentData(position, temp_ll_comments);

                            } else {
                                Toast.makeText(ctx, Constant.showErrorMsg(result.code, ctx), Toast.LENGTH_SHORT).show();
                            }

                        } catch (Exception e) {
                            Toast.makeText(ctx, Constant.NODATA, Toast.LENGTH_SHORT).show();
                        }

                    }
                }, null);

    }

    private class ViewHolder {
        private ImageView iv_head_pic;
        private TextView tv_name;
        private TextView tv_content;
        private GridViewForScrollView gv_photos;
        private TextView tv_loaction;
        private TextView tv_time;
        private TextView tv_delete;
        //        private ImageView iv_share;
        private ImageView iv_comment;
        private LinearLayout ll_comments;
    }

}
